<template>
  <div>
    <el-upload
        class="avatar-uploader"
        action="https://api.qchuhai.com/api/upload/image"
        :limit="limit"
        :accept="accept"
        list-type="picture-card"
        :file-list="fileList"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-preview="handlePictureCardPreview"
        :class="fileList.length === limit ? 'hide_box':''"
    >
      <el-icon><Plus /></el-icon>
      <template #tip>
        <div class="el-upload__tip">
          {{ acceptText }}
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible" width="30%">
      <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue';
import { ref, watch, nextTick  } from 'vue'
const emit = defineEmits(['saveImg'])
import type { UploadProps, UploadUserFile } from 'element-plus'
const dialogVisible = ref(false)
interface dataListInterface{
  url: string | undefined
}
const dialogImageUrl = ref('')
const fileList = ref<dataListInterface[]>([])
const props = defineProps({
  limit: {
    type: Number
  },
  accept: {
    type: String,
    default: '.png, .jpg'
  },
  acceptText: {
    type: String,
    default: ''
  },
  values: {
    type: Array,
    default: []
  }
})
watch(() => props.values, (a, pre) => { // watch函数监听props.playlist的值
  if (props.values.length > 0) {
    fileList.value = []
    props.values.forEach((item:any) => {
      nextTick(() => {
        fileList.value.push({
          url: item.url
        })
      })
    })
  } else {
    fileList.value = []
  }
},{immediate:true}) // immediate:true，让watch立即执行回调打印值
const  handleRemove = (file) => {
  if (props.limit === 1) {
    fileList.value = []
    emit('saveImg', [])
  } else {
    let url = ''
    if (file.response) {
      url = file.response.data.path
    } else {
      url = file.url
    }
    console.log(fileList.value)
    const findex = fileList.value.map(f =>{ return f.url } ).indexOf(url)
    emit('saveImg', fileList.value)
    if (findex > -1) {
      fileList.value.splice(findex, 1)
      emit('saveImg', fileList.value)
    }
  }
}
const handleSuccess = (data:any) => {
  fileList.value.push({
    url: data.data.path
  })
  emit('saveImg', fileList.value)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>
<style>
.hide_box .el-upload--picture-card{
  display: none;
}
*{
  outline: none !important;
}
</style>